<?php

/**
 * Description of LazyCollection
 * 
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Model;

use Nette;

class PageLazyCollection extends Nette\Object implements \IDataSource {

    private $mapper;
    private $query;
    private $limit;
    private $offset;

    public function __construct(IMapper $mapper, \DibiFluent $query) {
        $this->mapper = $mapper;
        $this->query = $query;
    }

    public function getIterator() {
        $result = $this->query->getIterator($this->limit, $this->offset);

        $data = array();
        foreach ($result as $row) {
            // vyžaduje load jako veřejnou metodu
            $data[$row->id] = $this->mapper->load($row);
        }

        return new \ArrayIterator($data);
    }

    public function where($cond) {
        if (func_num_args() > 1) {
            $cond = func_get_args();
        }

        $this->query->where('%ex', (array) $cond);

        return $this;
    }

    public function applyLimit($limit, $offset) {
        $this->limit = $limit;
        $this->offset = $offset;

        return $this;
    }
    
    public function getItemByUniqueId($id) {
        $row = $this->query->where("page.id = " . $id)->fetch();
        
        return $this->mapper->load($row);
    }
    
    public function getUniqueId($item) {
        return $item->id;
    }
    
    public function setSortable($column, $type) {
        $this->query->orderBy($column, $type);
    }
    
    public function orderBy(array $order) {
        $this->query->orderBy($order);
    }
    
    public function count() {
        return $this->query->count();
    }

}

